public class HelixMatrixII {
    /*
    * 螺旋矩阵 II
    * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
    * */

    public static void main(String[] args) {
        HelixMatrixII helixMatrixII = new HelixMatrixII();
        int n = 5;
        int[][] ints = helixMatrixII.mySolution(n);
        for(int r = 0; r < n; r++){
            for (int c = 0; c < n; c++){
                System.out.print(ints[r][c] + " ");
            }
            System.out.println();
        }
    }

    public int[][] mySolution(int n) {
        int[][] result = new int[n][n];
        int r=0, c=0, rowE=1, colE=1, next;
        int value=1;
        while(true){
            result[r][c] = value++;
            next = c+colE;
            if(next < n && next >= 0 && result[r][next] == 0){
                c = next;
            } else {
                colE = -colE;
                r += rowE;
                if(r < n && r >= 0 && result[r][c] == 0){
                    while(true){
                        result[r][c] = value++;
                        next = r+rowE;
                        if(next < n && next >= 0 && result[next][c] == 0){
                            r = next;
                        } else {
                            rowE = -rowE;
                            c += colE;
                            break;
                        }
                    }
                } else {
                    return result;
                }
            }
        }
    }
}
